#!/bin/bash

set -x
tssh_arch=$(arch)
tssh_version="${tssh_version:-0.1.22}"
tssh_name="tssh_${tssh_version}_linux_${tssh_arch}"
tssh_env_var="${tssh_env_var:-TSSH_HOME}"
tssh_download_path="/tmp/tssh-download"

rc_path="${rc_path:-${HOME}/.bashrc}"
softwares_path="${softwares_path:-/opt/softwares}"
tssh_home="${softwares_path}/${tssh_name}"
set +x

add_env_str=$(
  cat <<EOF

# ${tssh_env_var}
${tssh_env_var}="${tssh_home}"
export PATH="\${PATH}:\${${tssh_env_var}}"
EOF
)

download_tssh() {
  mkdir -p "${tssh_download_path}"
  echo "start download tssh..."
  curl -C - -o "${tssh_download_path}/${tssh_name}.tar.gz" -L0 \
    "https://ghproxy.cn/https://github.com/trzsz/trzsz-ssh/releases/download/v${tssh_version}/${tssh_name}.tar.gz"
  sudo mkdir -p "${softwares_path}"
  sudo rm -rf "${tssh_home}"
  sudo tar -C "${softwares_path}" -xzf "${tssh_download_path}/${tssh_name}.tar.gz"
}

main() {

  download_tssh

  if cat "${rc_path}" | grep -q "${tssh_env_var}"; then
    echo "find ${tssh_env_var} in ${rc_path}:"
    echo ''
    cat "${rc_path}" | grep "${tssh_env_var}"
    echo ''
    echo "please add tssh env var into ${rc_path} manally:"
    echo ""
    echo "${add_env_str}"
  else
    echo "${add_env_str}" >>"${rc_path}"
  fi
}

main
